<?php
namespace common\models;

use Yii;
use yii\base\Model;
class WechatLogin extends Model {
	public $openid;
	public $rememberMe = true;
	private $_user;
	
	/**
	 * @inheritdoc
	 */
	public function rules()
	{
		return [
			['openid', 'safe'],
			['rememberMe', 'boolean'],
		];
	}
	
	public function login()
	{
		if ($this->validate()) {
			Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
			return $this->getUser();
		} else {
			return false;
		}
	}
	
	/**
	 * Finds user by [[username]]
	 *
	 * @return User|null
	 */
	protected function getUser()
	{
		if ($this->_user === null) {
			$this->_user = $this->findByOpenid($this->openid);
		}
		return $this->_user;
	}
	
	/**
	 * 增加openid登录的方式
	 */
	
	public function findByOpenid($openid) {
		$user = User::findOne(['openid' => $openid]);
		if ($user) {
			//     		如果已经用户存在
			return $user;
		} else {
			$model = new User();
			$model->openid = $openid;
			$time = time();
			$model->created_at = $time;
			$model->created_at = $time;
			$model->status = User::STATUS_ACTIVE;
			if ($model->save()) {
				return $model;
			}
			//     		创建这个用户并返回
				
		}
	}
}